<template>
  <BasicDrawer v-bind="$attrs" @register="registerDrawer" :title="getTitle" width="50%" @ok="handleSubmit" destroyOnClose>
    <BasicForm @register="registerForm" />
  </BasicDrawer>
</template>
<script lang="ts" setup>
import {computed, ref, unref, useAttrs} from 'vue';
import {BasicForm, useForm} from '/@/components/Form/index';
import {commonFromSchema, ConfigPageType} from './payIfConfig.data';
import {BasicDrawer, useDrawerInner} from '/@/components/Drawer';
import {saveOrUpdatePayConfig} from './payIfConfig.api';
import {ColEx} from '/@/components/Form/src/types';
// 声明Emits
const emit = defineEmits(['success', 'register']);
const attrs = useAttrs()
const isUpdate = ref(true);
const rowId = ref('');


// 自适应列配置
const adaptiveColProps: Partial<ColEx> = {
  xs: 22, // <576px
  sm: 22, // ≥576px
  md: 22, // ≥768px
  lg: 22, // ≥992px
  xl: 22, // ≥1200px
  xxl: 22, // ≥1600px
}

//表单配置
const [registerForm, { setProps, resetFields, setFieldsValue, validate, resetSchema, appendSchemaByField }] = useForm({
  layout: 'vertical',
  labelWidth: '100%',
  showActionButtonGroup: false,
  wrapperCol: adaptiveColProps
});

//表单赋值
const [registerDrawer, { setDrawerProps, closeDrawer }] = useDrawerInner(async (data) => {
  await resetFields();
  console.log("payIfConfig: ", data.record);
  
  let showFooter = data?.showFooter ?? true
  setDrawerProps({ confirmLoading: false, showFooter })
  isUpdate.value = !!data?.isUpdate;
  let config: any = data.record.payIfConfig
  let schemas: any = []

  // 设置公共表单参数
  schemas.push.apply(schemas, commonFromSchema)
  schemas.push({
    field: config.ifName + "-" + config.mchTypeName + '-divider',
    component: 'Divider',
    label: config.ifName + " " + config.mchTypeName + "配置",
  })

  if (config.configPageType == ConfigPageType.JSON) {
    let configParams: any = []
    if (config.isMchMode == "1" && config.mchParams) {
      // 普通商户
      configParams = JSON.parse(config.mchParams)
    }
    if (configParams) {
      configParams.forEach(e => {
        schemas.push({
          field: e.field,
          label: e.label,
          show: e.show === undefined || e.show ? true : false,
          required: e.required ? e.required : false,
          componentProps: e.componentProps,
          helpMessage: e.helpMessage,
          defaultValue: e.defaultValue,
          component: e.component,
        })
      })
    }
    
    resetSchema(schemas)
    if (typeof config === 'object') {
      if (!config.ifParams) {
        config.ifParams = '{}'
      }
      let ifParams = {}
      try {
        ifParams = JSON.parse(config.ifParams)
      } catch(e) {
        console.error(e);
      }
      setFieldsValue({
        ...ifParams, ...config,
      })
    }
  } else {
    // 添加自定义页面
    resetSchema(schemas)
    if (typeof config === 'object') {
      setFieldsValue({
         ...config,
      })
    }
  }

  // 隐藏底部时禁用整个表单
  setProps({ disabled: !showFooter })
});
//获取标题
const getTitle = computed(() => (!unref(isUpdate) ? '新增支付接口配置' : '编辑支付接口配置'));

//提交事件
async function handleSubmit() {
  try {
    let values = await validate();
    setDrawerProps({ confirmLoading: true });
    let submitValues : any= {}
    submitValues.status = values.status
    submitValues.remark = values.remark
    submitValues.id = values.id

    delete values['status', 'remark', 'id']
    submitValues.ifParams = JSON.stringify(values)
    console.log("submit: ", submitValues);
    
    //提交表单
    await saveOrUpdatePayConfig(submitValues, unref(isUpdate));
    //关闭弹窗
    closeDrawer();
    //刷新列表
    emit('success', { isUpdate: unref(isUpdate), values: { ...values, id: rowId.value } });
  } finally {
    setDrawerProps({ confirmLoading: false });
  }
}
</script>
